package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.media.WantuService;
import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.BitmapUtils;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.ResultBean;
import com.ekuaitu.kuaitu.bean.UploadImageBean;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.ImageLoader;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SDCardUtils;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class CarSetupActivity extends AppCompatActivity implements UploadListener, AMapLocationListener {

    @BindView(R.id.car_front_seat)
    ImageView carFrontSeat;
    @BindView(R.id.car_rear_seat)
    ImageView carRearSeat;
    @BindView(R.id.car_left)
    ImageView carLeft;
    @BindView(R.id.car_front)
    ImageView carFront;
    @BindView(R.id.car_right)
    ImageView carRight;
    @BindView(R.id.car_rear)
    ImageView carRear;
    @BindView(R.id.progress_bar)
    RelativeLayout progressBar;
    @BindView(R.id.setup_timer)
    TextView setupTimer;
    @BindView(R.id.setup_commit)
    TextView setupCommit;
    @BindView(R.id.setup_image)
    ImageView setupImage;
    @BindView(R.id.car_setup_up_commit)
    TextView carSetupUpCommit;

    private static final int REQ_TAKE_PHOTO = 200;

    private Context mContext = this;
    private String[] token = new String[]{"", "", "", "", "", ""};
    private String[] key = new String[]{"", "", "", "", "", ""};
    private int clickPosition = 3;  //点击的哪个图片上传
    private WantuService wantuService;
    private File compressFile;
    private UploadListener mListener = this;
    private ArrayList<String> pics = new ArrayList<>();
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private boolean isRemainingTime = true;
    private File originalFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_setup);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        WantuService.enableHttpDNS();
        WantuService.enableLog();
        wantuService = WantuService.getInstance();
        wantuService.asyncInit(this);

        countDown(getIntent().getLongExtra("remainingTime", 600000));  //10分钟倒计时
        ImageLoader.getInstance().displayImage(getApplicationContext(), MyApplication.getInstance().getImageUrl() + getIntent().getStringExtra("picId"), setupImage);
        getLocationPermission();

    }

    private void getLocationPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //定位权限
        if (requestCode == 1) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ToastCompat.makeText(mContext, "您已拒绝相机权限，将不能拍照", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1://开始压缩
                    progressBar.setVisibility(View.VISIBLE);
                    pics.add(msg.getData().getString("originalPath"));
                    break;
                case 2://成功压缩
                    String pathName = msg.getData().getString("compressPath");
                    pics.add(pathName);
                    //上传图片
                    compressFile = new File(pathName);
                    uploadImage(compressFile);
                    break;
                case 3://压缩失败
                    progressBar.setVisibility(View.GONE);
                    key[clickPosition] = "";
                    ToastCompat.makeText(mContext, "图片压缩失败，请重试", Toast.LENGTH_LONG).show();
                    break;
                case 4: //上传成功
                    progressBar.setVisibility(View.GONE);
                    switch (clickPosition) {
                        case 0:
                            Glide.with(getApplicationContext()).load(compressFile).into(carFrontSeat);
                            //carFrontSeat.setImageURI(Uri.fromFile(compressFile));
                            break;
                        case 1:
                            Glide.with(getApplicationContext()).load(compressFile).into(carRearSeat);
                            //carRearSeat.setImageURI(Uri.fromFile(compressFile));
                            break;
                        case 2:
                            Glide.with(getApplicationContext()).load(compressFile).into(carLeft);
                            //carLeft.setImageURI(Uri.fromFile(compressFile));
                            break;
                        case 3:
                            Glide.with(getApplicationContext()).load(compressFile).into(carFront);
                            //carFront.setImageURI(Uri.fromFile(compressFile));
                            break;
                        case 4:
                            Glide.with(getApplicationContext()).load(compressFile).into(carRight);
                            //carRight.setImageURI(Uri.fromFile(compressFile));
                            break;
                        case 5:
                            Glide.with(getApplicationContext()).load(compressFile).into(carRear);
                            //carRear.setImageURI(Uri.fromFile(compressFile));
                            break;
                    }
                    ToastCompat.makeText(mContext, getMes(clickPosition) + "照片上传成功", Toast.LENGTH_SHORT).show();
                    break;
                case 5://上传失败
                    progressBar.setVisibility(View.GONE);
                    key[clickPosition] = "";
                    ToastCompat.makeText(mContext, msg.getData().getString("failReason"), Toast.LENGTH_SHORT).show();
                    break;
                case 6://上传取消
                    progressBar.setVisibility(View.GONE);
                    key[clickPosition] = "";
                    ToastCompat.makeText(mContext, "图片上传取消", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };


    //百川上传图片
    @Override
    public void onUploading(UploadTask uploadTask) {

    }

    @Override
    public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
        Message message = new Message();
        message.arg1 = 5;
        Bundle b = new Bundle();
        b.putString("failReason", failReason.getMessage());
        message.setData(b);
        handler.sendMessage(message);
    }

    @Override
    public void onUploadComplete(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 4;
        handler.sendMessage(message);

    }

    @Override
    public void onUploadCancelled(UploadTask uploadTask) {
        Message message = new Message();
        message.arg1 = 6;
        handler.sendMessage(message);
    }


    private void uploadImage(final File picFile) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).uploadImage(MyApplication.getInstance().getRequestFieldMap(), "jpg", "", "", "", "1", "1", "kuaitu").enqueue(new Callback<UploadImageBean>() {
            @Override
            public void onResponse(Call<UploadImageBean> call, Response<UploadImageBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        //从服务器获取图片的token，key，给百川上传是用token，提交照片时，把对应的key给服务器
                        token[clickPosition] = response.body().getAttachment().getToken();
                        key[clickPosition] = response.body().getAttachment().getKey();
                        wantuService.upload(picFile, mListener, token[clickPosition]);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UploadImageBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @OnClick({R.id.iv_setup_return, R.id.camera_left, R.id.car_left, R.id.camera_right, R.id.car_right, R.id.camera_front, R.id.car_front,
            R.id.camera_rear, R.id.car_rear, R.id.camera_front_seat, R.id.car_front_seat, R.id.camera_rear_seat, R.id.car_rear_seat,
            R.id.setup_commit, R.id.car_setup_up_commit})
    public void onClick(View view) {
        originalFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + new SDCardUtils().createFileName("Kuaitu", ".jpg"));
        switch (view.getId()) {
            case R.id.iv_setup_return:
                intentToInvite();

                break;
            case R.id.car_front_seat:
            case R.id.camera_front_seat:
                if (isRemainingTime) {
                    clickPosition = 0;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.car_rear_seat:
            case R.id.camera_rear_seat: {
                if (isRemainingTime) {
                    clickPosition = 1;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.car_left:
            case R.id.camera_left:
                if (isRemainingTime) {
                    clickPosition = 2;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.car_front:
            case R.id.camera_front:
                if (isRemainingTime) {
                    clickPosition = 3;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.car_right:
            case R.id.camera_right:
                if (isRemainingTime) {
                    clickPosition = 4;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.car_rear:
            case R.id.camera_rear:
                if (isRemainingTime) {
                    clickPosition = 5;
                    intentCamera();
                } else {
                    ToastCompat.makeText(mContext, "您已超时，无法提交审核", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.car_setup_up_commit:
            case R.id.setup_commit:
                if (isRemainingTime) {
                    for (int i = 0; i < key.length; i++) {
                        if (key[i] == null || key[i].equals("")) {
                            ToastCompat.makeText(mContext, "请上传" + getMes(i) + "照片", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    startLocation();
                } else {
                    final KuaituDialog kuaituDialog = new KuaituDialog(CarSetupActivity.this);
                    kuaituDialog.setTitle(getString(R.string.dialogTitle));
                    kuaituDialog.setMessage("您已超时，无法提交审核");
                    kuaituDialog.setYesOnclickListener("确认", new KuaituDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            kuaituDialog.dismiss();
                            finish();
                        }
                    });
                    kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            kuaituDialog.dismiss();
                            finish();
                        }
                    });
                    kuaituDialog.setCancelable(false);
                    kuaituDialog.show();
                }
                break;
        }
    }

    private void intentCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {//判断是否有相机应用
            Uri photoURI = FileProvider.getUriForFile(CarSetupActivity.this, "com.ekuaitu.fileprovider", originalFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQ_TAKE_PHOTO);
        }
    }

    private void startLocation() {
        mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        progressBar.setVisibility(View.VISIBLE);
    }


    //提交
    private void commit(String longitude, String latitude) {
        String keys = "";
        for (int i = 0; i < key.length; i++) {
            keys += key[i] + ",";
        }
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).commitSetup(MyApplication.getInstance().getRequestFieldMap(), Constants.orderId, keys, longitude, latitude).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                progressBar.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus().equals("200")) {
                        ToastCompat.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                        intentToInvite();

                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void intentToInvite() {
        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_SHARE_INVITE) == 1) {
            Intent intent = new Intent(mContext, InviteActivity.class);
            intent.putExtra(IntentKey.SHARE_TYPE, 1);  //1从支付页面跳分享  2个人中心跳分享
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private String getMes(int i) {
        String mes = "";
        switch (i) {
            case 0:
                mes = "前座";
                break;
            case 1:
                mes = "后座";
                break;
            case 2:
                mes = "左侧";
                break;
            case 3:
                mes = "车头";
                break;
            case 4:
                mes = "右侧";
                break;
            case 5:
                mes = "车尾";
                break;
        }
        return mes;
    }

    private CountDownTimer timer;
    private PowerManager.WakeLock wakeLock;

    //倒计时
    private void countDown(long placeOrderTimer) {
        timer = new CountDownTimer(placeOrderTimer, 1000) {
            @Override
            public void onTick(long l) {
                setupTimer.setText("还剩 " + TimeUtils.formatSecondCount(l / 1000 + "", 2) + " 结束");
            }

            @Override
            public void onFinish() {
                isRemainingTime = false;
                setupTimer.setText("已结束");
                carSetupUpCommit.setTextColor(getResources().getColor(R.color.card_line));
                setupCommit.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_unclick));
            }
        };
        timer.start();
        acquireWakeLock();
    }


    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }


    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
            releaseWakeLock();
        }
        if (pics != null && pics.size() != 0) {
            for (int i = 0; i < pics.size(); i++) {
                SDCardUtils.removeFileFromSDCard(pics.get(i));
            }
        }

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            commit(aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "");
        } else {
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_TAKE_PHOTO://返回结果
                if (resultCode != Activity.RESULT_OK) {
                    return;
                }

                Luban.with(this)
                        .load(originalFile)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                Message message = new Message();
                                message.arg1 = 1;
                                Bundle b = new Bundle();
                                b.putString("originalPath", originalFile.getAbsolutePath());
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onSuccess(File file) {
                                Message message = new Message();
                                message.arg1 = 2;
                                Bundle b = new Bundle();
                                b.putString("compressPath", file.getAbsolutePath());
                                message.setData(b);
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Message message = new Message();
                                message.arg1 = 3;
                                handler.sendMessage(message);
                            }
                        }).launch();    //启动压缩
                break;
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        intentToInvite();
    }
}